<template>
  <div class="chart-outer" style="min-height: 200px;">

  </div>
</template>

<script>
import * as echarts from 'echarts';
import s94Mjs from "s94-js";
export default {
  name: "chart",
  props: ['type', 'datasets', 'labels', 'options'],
  data(){
    return {
      update_ing: false,
    }
  },
  methods: {
    get_option(){
      let res = {
        xAxis: {
          type: 'category',
          data: this.labels,
        },
        yAxis: {
          type: 'value'
        },
        series: []
      };
      let count = this.labels.length;
      let datasets = this.datasets instanceof Array ? this.datasets : [this.datasets];
      let type_map = ['line', 'bar', 'pie'];
      datasets.forEach(function (v){
        let row = {};
        row.type = ~type_map.indexOf(v.type) ? v.type : 'line';
        let data = v.data || [];
        for (let i = 0; i < count-data.length; i++) { data.push(0); }
        row.data = data;
        row.name = v.name || v.label || v.title || '';
        res.series.push(row);
      })
      if (typeof(this.options) == 'object'){
        res = s94Mjs.merge(this.options, res)
      }
      return res;
    },
    update(timeout){
      let app = this;
      if (app.update_ing || !app.chart) return;
      app.update_ing = true;
      setTimeout(function(){
        app.update_ing = false;
        let option = app.get_option();
        app.chart.setOption(option);
      }, timeout);
    },
  },
  watch: {

  },
  updated() {
    this.update(10);
  },
  mounted() {
    let app = this;
    app.chart = echarts.init(this.$el);
    app.update(0);
  }
}
</script>

<style scoped>

</style>